import { defineStore } from "pinia";
import pinia from "@/store";
import { userLogin, refreshUserInfo } from "@/api/user";
import type { IuserState, LoginRequest } from './types'  // 使用types文件中的类型

export const useUserStoreHook = defineStore('userInfo', {
  state: (): IuserState => ({
    username: "小邦这厢有礼了",
    accessToken: "",
    refreshToken: "",
    roles: ['common'],
  }),
  actions: {
    storeUserLogin(data: LoginRequest) {
      return userLogin(data).then((res) => {
        this.username = res.username;
        this.roles = res.roles;
        this.accessToken = res.accessToken;
        return res;
      })
    },
    storeRefreshUserInfo() {
      if (this.username == '小邦这厢有礼了' && this.accessToken != '') {
        refreshUserInfo({
          accessToken: this.accessToken,
        })
        .then((res) => {
          this.username = res.username;
          this.roles = res.roles;
          this.accessToken = res.accessToken;
        }).catch(() => {
          this.accessToken = '';
        })
      }
    }
  },
  persist: {
    key: 'userInfo',
    storage: sessionStorage,
    paths: ['accessToken'],
  },
});

// 导出统一的 store hook
export function useUserStore() {
  return useUserStoreHook(pinia)
}